package xin.petstore.framework.web.img.controller;

import xin.petstore.framework.cache.RedisSpecMethods;
import xin.petstore.framework.web.img.Cm;
import xin.petstore.framework.web.img.ImageUtils;
import xin.petstore.framework.web.img.dbmanager.ImgCodeRepositoryDao;
import xin.petstore.framework.utils.IPUtils;
import xin.petstore.framework.cache.redis.RedisService;
import xin.petstore.framework.cas.SessionUtils;
import xin.petstore.framework.utils.ObjectUtils;
import xin.petstore.framework.utils.SpringContextHolder;
import com.mongodb.gridfs.GridFSDBFile;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * =============================
 * Author: 
 * Function: 图片验证码
 * Version: 1.0
 * Date: 2016/7/4 0004
 * =============================
 */
@Controller
@RequestMapping("/randCodeImage")
public class RandCodeImage  implements Cm{
    public static final Logger logger = LoggerFactory.getLogger(RandCodeImage.class);
    private ImgCodeRepositoryDao imgCodeRepositoryDao = SpringContextHolder.getBean("imgCodeRepositoryDao");
    private RedisService redisService = SpringContextHolder.getBean("redisService");
    private static Random rand = new Random();
    private static final String tip = "Hi，你这是在玩嘻唰唰吗？慢点来吧！";
    private static final String errors = "Hi~，加载出错了，请稍等会吧...";

    @RequestMapping(method={RequestMethod.GET})
    public void domain(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0L);
        response.setContentType("image/jpeg");
        response.addDateHeader("Last-Modified",System.currentTimeMillis()-86400);
        ServletOutputStream out = response.getOutputStream();
        StringBuffer buffer = new StringBuffer();
        List<byte[]> byteList = new ArrayList<byte[]>();
        String ipyuan = IPUtils.getRemoteAddr(request);
        try {
            String url = request.getRequestURI().toString();
            String lock_key = buffer.append(ipyuan).append("-").append(url).append("-").append(FLAG).toString();
            Object blackip =redisService.getObject(lock_key + BLACK_LIST);
            String ipCount = RedisSpecMethods.getValue(lock_key);
            if ( (ipCount != null && Integer.parseInt(ipCount.toString()) > COUNT_LIMIT) || ObjectUtils.isNotNullOrEmpty(blackip)) {
                out.write(IOUtils.toByteArray(ImageUtils.tipForImages(tip, IMAGE_TYPE)));
                out.flush();
                out.close();
                return;
            } else {
                Long reqCount = RedisSpecMethods.incrBy(lock_key, TIME_LIMIT, 1);// 请求次数
                if (reqCount > COUNT_LIMIT) {
                    redisService.setObject(lock_key + BLACK_LIST, lock_key, FORBIDEN_TIME_LIMIT, TimeUnit.SECONDS);
                    out.write(IOUtils.toByteArray(ImageUtils.tipForImages(tip, IMAGE_TYPE)));
                    out.flush();
                    out.close();
                    return;
                }
            }
        } catch (Exception e) {
            logger.error("#验证码#缓存加载失败.", e );
            out.write(IOUtils.toByteArray(ImageUtils.tipForImages(errors, IMAGE_TYPE)));
            out.flush();
            out.close();
        }

        try {
            List filter = imgCodeRepositoryDao.getRandomList(4);
            List<GridFSDBFile> imgGridFSList = imgCodeRepositoryDao.getGridFSList(filter);
            System.out.println("#############################"+imgGridFSList.size());
            for (int i = 0; i < imgGridFSList.size(); i++) {
                InputStream inputStream = imgGridFSList.get(i).getInputStream();
                byteList.add(IOUtils.toByteArray(inputStream));
            }
            int ran = rand.nextInt(filter.size());
            SessionUtils.getSession().setAttribute("rand", ran+1);
            ByteArrayInputStream byteArrayInputStream = ImageUtils.waterMarkImage(byteList, IMAGE_TYPE, filter.get(ran).toString());
            out.write(IOUtils.toByteArray(byteArrayInputStream));
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.error("#验证码#图片加载失败.", e );
        	 out.write(IOUtils.toByteArray(ImageUtils.tipForImages(errors, IMAGE_TYPE)));
             out.flush();
             out.close();
        }


    }

}